package com.hp.btc.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.hp.btc.util.ftp.SendFile;

public class JsonCustomResources {

	private static final Logger logger = LoggerFactory.getLogger(JsonCustomResources.class);

	private String rootFileJson;
	private String rootFileTmpJson;
	public final SimpleDateFormat dateFormatwithmiliseconds = new SimpleDateFormat(
			"yyyyMMddHHmmssSSS");
	
	private String ipClient;
	
	@Autowired
	SendFile sendFile;

	public JsonCustomResources() {
	}

	public JsonCustomResources(String rootFileJson) {
		this.rootFileJson = rootFileJson;
	}

	public <T> T readFiletoPath(T clazz, final String filePath) {
		logger.info("readFiletoPath " + filePath);
		rootFileJson = filePath;
		ObjectMapper mapper = new ObjectMapper();
		try {
			FileReader fileReader = new FileReader(filePath);
			clazz = mapper.readValue(fileReader, (Class<T>) clazz);

			// logger.info(clazz.toString());
		} catch (FileNotFoundException e) {
			logger.error("**FileNotFound**", e);
		} catch (IOException e) {
			logger.error("**IOException**", e);
		}
		return clazz;
	}

	public <T> T readFiletoPath(T clazz) {
		return this.readFiletoPath(clazz, rootFileJson);
	}

	public void writeFiletoPath(Object obj) {
		String fileRename = generateBackup(rootFileJson);
		writeFiletoPath(rootFileJson, obj);
		syncronitedFiletoServers(fileRename);
	}

	public void writeFiletoPath(String filePath, Object obj) {
		logger.info("** writeFiletoPath  {}", filePath);
		ObjectMapper mapper = new ObjectMapper();
		try {
			rootFileTmpJson = filePath;
			File file = new File(filePath);
			mapper.writerWithDefaultPrettyPrinter();
			mapper.writeValue(file, obj);
		} catch (FileNotFoundException e) {
			logger.error("**FileNotFound**", e);
		} catch (IOException e) {
			logger.error("**IOException**", e);
		}
	}
	
	public String generateBackup(String filePath){
		logger.info("** generateBackup  {}", filePath);
		File fileOrigen = new File(filePath);
		String newFileName = filePath.replaceFirst("\\.json", getFormatterDateuntilMilliseconds(new Date()).concat(".json"));
		File fileRename = new File(newFileName);
		
		boolean isOk = fileOrigen.renameTo(fileRename);
		logger.info(" File renamed? ==> "+isOk);
		logger.info("filePath {}", fileOrigen.getName());
		
		return fileRename.getAbsolutePath();
	}
	
	public void syncronitedFiletoServers(String path){
		logger.info("preparate to send files into servers into directory:");
		logger.info("find path==>"+path);
		File file = new File(path);
		try {
			sendFile.sendFileSFTPServers(file.getParent(), file.getName(), ipClient);
		} catch (Exception e) {
			logger.error("Error sendFilestoServer", e);
		}
	}

	public String getFormatterDateuntilMilliseconds() {
		return getFormatterDateuntilMilliseconds(new Date());
	}

	public String getFormatterDateuntilMilliseconds(Date date) {
		if (date == null)
			date = new Date();
		return dateFormatwithmiliseconds.format(date);
	}

	public String getRootFileTmpJson() {
		return rootFileTmpJson;
	}

	public String getRootFileJson() {
		return rootFileJson;
	}

	public String formatStringServiceHour(String serviceOutHour) {
		if (!StringUtils.hasText(serviceOutHour))
			return "";
		if (org.apache.commons.lang3.StringUtils.containsAny(serviceOutHour,
				"|")) {
			return formatStringServiceHour(StringUtils
					.delimitedListToStringArray(serviceOutHour, "|"));
		} else {
			String[] newString = new String[1];
			newString[0] = serviceOutHour;
			return formatStringServiceHour(newString);
		}
	}

	public String formatStringServiceHour(String[] serviceOutHour) {
		StringBuffer strBuffer = new StringBuffer();
		String[] letterDayofWeek = new String[] { "D", "L", "MA", "MI", "J",
				"V", "S" };
		String numberDayofWeek = "";
		String hourofDayStar = "";
		String hourofDayEnd = "";
		int count = 1;
		Map<Integer, String> mapBuffer = new HashMap<Integer, String>();
		for (String capitalLetter : letterDayofWeek) {
			mapBuffer.put(count++, capitalLetter.concat(" OFF|"));
		}
		String[] orderedHour = StringUtils.sortStringArray(serviceOutHour);
		logger.info("orderedHour {}", orderedHour);
		for (String outHour : orderedHour) {
			numberDayofWeek = outHour.substring(0, 1);
			hourofDayStar = outHour.substring(1, 3);
			hourofDayEnd = outHour.substring(3, 5);

			String dayofweek = mapBuffer.get(Integer.parseInt(numberDayofWeek));
			String replaceValue = "ON ".concat(hourofDayStar + " ").concat(
					hourofDayEnd);
			String replacing = dayofweek.replaceFirst("OFF", replaceValue);

			mapBuffer.put(Integer.parseInt(numberDayofWeek), replacing);
		}
		for (String value : mapBuffer.values()) {
			strBuffer.append(value);
		}
		strBuffer.delete(strBuffer.length() - 1, strBuffer.length());
		return strBuffer.toString();
	}

	public String getIpClient() {
		return ipClient;
	}

	public void setIpClient(String ipClient) {
		this.ipClient = ipClient;
	}
	

}
